package com.mikewoo.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;


/**
 * Title: AioServerDemo.java
 * Description: 利用AIO实现的服务端程序
 * 
 * author     Phantom
 * date       2016年5月20日 上午10:19:49
 * @version    1.0.0
 */
public class AioServerDemo {
	private static CountDownLatch latch;
	public static void startServer() throws Exception {
		final AsynchronousServerSocketChannel asyServerSocketChannel = AsynchronousServerSocketChannel.open();
		asyServerSocketChannel.bind(new InetSocketAddress(8999));
		
		latch = new CountDownLatch(1);
		
		asyServerSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

			public void completed(AsynchronousSocketChannel asyChannel, Void attachment) {
				try {
					asyServerSocketChannel.accept(attachment, this);
					operate(asyChannel);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			public void failed(Throwable exc, Void attachment) {
				latch.countDown();
			}
			
		});
		
		latch.await();
	}
	
	private static void operate(AsynchronousSocketChannel asyChannel) throws Exception {
		ByteBuffer byteBuffer = ByteBuffer.allocate(48);
		int size = asyChannel.read(byteBuffer).get();
		while (size > 0) {
			byteBuffer.flip();
			Charset charset = Charset.forName("UTF-8");
			System.out.println(charset.newDecoder().decode(byteBuffer));
			byteBuffer.clear();
			size = asyChannel.read(byteBuffer).get();
		}
		byteBuffer.clear();
	}
	
	public static void main(String[] args) throws Exception {
		startServer();
	}
}
